<template>
  <basic-container class="app-container">
    <div class="filter_container">
      <el-form :inline="true" :model="commodityform" class="demo-form-inline" style="display:block">
        <el-form-item label="商品名称">
          <el-input
            v-model.trim="commodityform.name"
            size="small"
            clearable
            placeholder="请输入商品名称"
            @keyup.enter.native="handleFiltercommodityform"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select
            ref="goodsStateref"
            v-model="commodityform.goodsState"
            clearable
            placeholder="请选择商品状态"
            size="small"
            @keydown.native="selectBlur($event)"
          >
            <el-option
              v-for="item in PoundstatusList"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维护类型">
          <el-select
            ref="maintainRef"
            v-model="commodityform.maintain"
            clearable
            placeholder="请选择维护类型"
            size="small"
            @keydown.native="selectBlur($event)"
            @keyup.enter.native="$event.target.blur"
          >
            <el-option
              v-for="item in maintainList"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配料表状态">
          <el-select
            ref="materielStateRef"
            v-model="commodityform.materielState"
            clearable
            placeholder="请选择配料表状态"
            size="small"
            @keydown.native="selectBlur($event)"
          >
            <el-option
              v-for="item in ingredientsList"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品类型">
          <el-cascader
            ref="categoryRef"
            v-model="categoryId"
            clearable
            placeholder="请选择商品类型"
            :options="categoriesList"
            @change="selectCategory(categoryId)"
            :show-all-levels="false"
            @keyup.enter.native="$event.target.blur"
            @blur="selectBlur($event)"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="sku码">
          <el-input
            v-model.trim="commodityform.skuCode"
            size="small"
            clearable
            placeholder="请输入sku码"
            @keyup.enter.native="handleFiltercommodityform"
          ></el-input>
        </el-form-item>
        <el-form-item width="300px">
          <el-checkbox v-model="clickFramingchecked" border="" size="small">
            <span>全国</span>
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            plain
            @click="handleFiltercommodityform"
            icon="el-icon-search"
            size="small"
          >查询</el-button>
        </el-form-item>
        <el-form-item>
          <div style="border:none" class="addshop" v-if="permission.commodity_add">
            <el-dropdown @command="handleCreate">
              <el-button type="primary" size="small">
                新建商品<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="single">
                  单个商品
                </el-dropdown-item>
                <el-dropdown-item command="commodity">
                  组合商品
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button size="small" icon="el-icon-download" @click="handleExport">
            导出
          </el-button>
          <el-button size="small" icon="el-icon-edit" @click="handleBatchEdit" v-xmbz-permission="'commodity_batch_edit'">
            批量修改
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      class="table_list"
      :data="commodityList"
      border=""
      fit
      highlight-current-row
      style="width: 100%;"
      :row-class-name="tableRowClassName"
    >
      <el-table-column label="商品ID" prop align="center" width="160px">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="sku码" prop align="center" width="150px">
        <template slot-scope="{row}">
          <span v-for="(item, index) in row.goodsSkuS">
            {{ item.skuCode }}
            <span v-if="index < row.goodsSkuS.length - 1">/</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="商品规格" prop align="center" width="150px">
        <template slot-scope="{row}">
          <span v-for="(item, index) in row.goodsSkuS">
            {{ item.specs }}
            <span v-if="index < row.goodsSkuS.length - 1">/</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品简称" align="center" prop="alias" width="200px"></el-table-column>
      <el-table-column label="配料表状态" prop align="center" width="100px">
        <template slot-scope="{row}">
          <span>{{ changematerStateName(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" prop align="center">
        <template slot-scope="{row}">
          <span>{{ row.categoryName }}-{{ row.minCategoryName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品状态" align="center" width="80px" prop="goodsState">
        <template slot-scope="{row}">
          <span>{{ row.goodsStateName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop align="center">
        <template slot-scope="{row}">
          <el-button
            v-if="permission.commodity_edit"
            class="mb-5"
            type="warning"
            size="mini"
            @click="row.isCombination=='1'?handleDeit(row):handlecomDeit(row)"
            onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}"
          >编辑</el-button>
          <el-button
            v-if="permission.commodity_add"
            class="mb-5"
            size="mini"
            @click="handleCopy(row)"
            onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}"
          >复制</el-button>
          <el-button
            v-if="permission.commodity_del"
            class="mb-5"
            type="danger"
            size="mini"
            @click="handleDelete(row)"
            onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="commodityform.page"
      :limit.sync="commodityform.size"
      layout="sizes,prev, pager, next,total"
      @pagination="getList"
    />
    
    <addSingleGoodsDialog ref="addSingleGoodsDialog" :clickFramingchecked="clickFramingchecked" @getList="getList"></addSingleGoodsDialog>
    <addCommodityGoodsDialog ref="addCommodityGoodsDialog" :clickFramingchecked="clickFramingchecked" @getList="getList"></addCommodityGoodsDialog>
    <batchEditGoodsDialog ref="batchEditGoodsDialog" @editSuccess="getList"></batchEditGoodsDialog>
  </basic-container>
</template>

<script>
import {
  Categories, // 商品类型
  CakeWhereaboutsList, //商品状态
  goodsList, //列表
  deleteGoods, //删除
  downLoadGoodsExcel,
} from "@/api/commodityfiles";
//引入图片
import Pagination from "@/components/Pagination"; //分页
import { mapGetters } from 'vuex'
import addSingleGoodsDialog from './components/addSingleGoodsDialog'
import addCommodityGoodsDialog from './components/addCommodityGoodsDialog'
import batchEditGoodsDialog from './components/batchEditGoodsDialog'
import {download, downloadByUrl} from '@/util/file'

export default {
  components: {
    Pagination,
    addSingleGoodsDialog,
    addCommodityGoodsDialog,
    batchEditGoodsDialog,
  },
  data() {
    return {
      // start------------------------------------------------------------
      // 列表部分------------------------------------------------------------
      commodityform: {
        //查询条件
        deptId: "",
        name: "", //商品名称
        goodsState: "", //商品状态
        categoryId: "", //商品类型
        skuCode: "", //sku
        maintain: "", //维护类型
        materielState: "", //配料表状态

        page: 1,
        size: 10
      },
      PoundstatusList: [], //商品状态
      categoriesList: [], //商品类型列表
      categoryId: [], //商品类型列表

      commodityList: [
        // 商品列表
      ],
      clickFramingchecked: true, //全国
      total: 0,
      listLoading: true,
      caketype: false,
      cityareaId: "",
      // 维护类型
      maintainList: [
        {
          dictKey: 1,
          dictValue: "已维护"
        },
        {
          dictKey: 3,
          dictValue: "未维护"
        }
      ],
      // 配料
      ingredientsList: [
        {
          dictKey: 1,
          dictValue: "已上传"
        },
        {
          dictKey: 2,
          dictValue: "未上传"
        }
      ], //配料表
    };
  },
  computed: {
    ...mapGetters(["permission"]),
  },
  watch: {
  },
   created() {
    document.onkeydown = (e) => {
      var key = window.event.keyCode
      if (key === 13) {
        this.$msgbox.close()
      }
    }
  },
  mounted() {
    var saberareaIds = JSON.parse(localStorage.getItem("saber-areaId"));
    this.cityareaId = saberareaIds["content"];
    this.getList();
    this.getCategoriesList(); //查蛋糕类型
    this.getCakeWhereaboutsList(); // 商品状态
    window.addEventListener("keydown", this.keyupEnter);
  },
  methods: {
    changematerStateName(item){
      let title = (item.goodsSkuS.length && item.goodsSkuS.every(item => item.materielState == 1)) ? '已上传' : '未上传'
      return title
    },
    selectBlur(e) {
      if (e.keyCode == 13) {
        this.$refs["goodsStateref"].blur();
        this.$refs["maintainRef"].blur();
        this.$refs["materielStateRef"].blur();
        e.returnValue = false;
      }
    },
    // 回车事件
    keyupEnter() {
      if (window.event.keyCode == 13) {
        this.handleFiltercommodityform(); // 查询事件
      }
    },
    
    // 公共部分--------------------------------------------------------------------------------
    tableRowClassName({
      //表格样式
      row
    }) {
      if (row.isOnSale === 3) {
        return "warning-row";
      }
      return "";
    },
    getCakeWhereaboutsList() {
      CakeWhereaboutsList("").then(response => {
        this.PoundstatusList = response.data.data;
      });
    },
    getCategoriesList() {
      //蛋糕类型
      Categories("").then(response => {
        const batchdata = response.data.data;
        const dataValueBatch = batchdata =>
          batchdata.map(
            ({ id, categoryName, children }) =>
              children
                ? {
                    value: id,
                    label: categoryName,
                    children: dataValueBatch(children)
                  }
                : {
                    value: id,
                    label: categoryName
                  }
          );
        this.categoriesList = dataValueBatch(batchdata);
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },

    selectCategory(selected) {
      //选择蛋糕类型
      this.commodityform.categoryId = selected;
    },
    // 商品列表页面部分
    handleFiltercommodityform() {
      //查询
      this.commodityform.page = 1;
      this.getList();
    },
    getList() {
      //列表数据
      this.listLoading = true;
      goodsList(this.getParams()).then(response => {
        this.commodityList = response.data.data.rows;
        this.total = response.data.data.total;
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },
    getParams() {
      return {
        ...this.commodityform,
        deptId: this.clickFramingchecked ? 1 : this.cityareaId,
        categoryId: this.categoryId && this.categoryId.length && this.categoryId[this.categoryId.length - 1],
      }
    },
    handleDelete(row) {
      if (row.deptId == 1) {
        if (this.clickFramingchecked == true) {
          this.$confirm(
            "删除商品后,全国其他城市同一商品会同步删除,是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
          )
            .then(() => {
              deleteGoods({
                goodsId: row.id
              }).then(() => {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                this.getList();
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除"
              });
            });
        } else {
          this.$message({
            type: "warning",
            message: "不能删除该商品,需要勾选全国按钮去编辑"
          });
          return false;
        }
      } else {
        this.$confirm("是否删除该城市下的当前商品?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            deleteGoods({
              goodsId: row.id
            }).then(() => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getList();
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      }
    },

    // 单个商品-----------------------------------------------
    handleSingleproduct() {
      //添加单个商品
      this.$refs.addSingleGoodsDialog.show({ status: 'create' })
    },
    handleDeit(item) {
      if (item.deptId == 1) {
        if (this.clickFramingchecked == true) {
          //城市ID为1及选中全国
          this.$confirm(
            "编辑商品后,全国其他城市同一商品会同步修改, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
              closeOnClickModal: false,
            }
          )
            .then(() => {
              this.$refs.addSingleGoodsDialog.show({
                status: 'update',
                data: item
              })
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消修改"
              });
            });
        } else {
          this.$message({
            type: "warning",
            message: "不能编辑该商品,需要勾选全国按钮去编辑"
          });
          return false;
        }
      } else {
        this.$refs.addSingleGoodsDialog.show({
          status: 'update',
          data: item
        })
      }
    },
    //组合商品-----------------------------------------------
    handleCommodity() {
      //添加组合商品
      this.$refs.addCommodityGoodsDialog.show({ status: 'create' })
    },
    handlecomDeit(item) {
      // console.log(item,2)
      if (item.deptId == 1) {
        if (this.clickFramingchecked == true) {
          //城市ID为1及选中全国
          this.$confirm(
            "编辑商品后,全国其他城市同一商品会同步修改, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
          )
            .then(() => {
              this.$refs.addCommodityGoodsDialog.show({
                status: 'update',
                data: item
              })
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消修改"
              });
            });
        } else {
          this.$message({
            type: "warning",
            message: "不能编辑该商品,需要勾选全国按钮去编辑"
          });
          return false;
        }
      } else {
        this.$refs.addCommodityGoodsDialog.show({
          status: 'update',
          data: item
        })
      }
    },
    handleCreate(command) {
      if (command === 'single') {
        this.handleSingleproduct()
      } else if (command === 'commodity') {
        this.handleCommodity()
      }
    },
    handleCopy(item) {
      if (item.isCombination == 1) {
        this.$refs.addSingleGoodsDialog.show({
          status: 'copy',
          data: item
        })
      } else {
        this.$refs.addCommodityGoodsDialog.show({
          status: 'copy',
          data: item
        })
      }
    },
    handleExport() {
      downloadByUrl('/api/xmbz-goods/goods/downLoadGoodsExcel', this.getParams())
      // downLoadGoodsExcel(this.getParams()).then(res => {
      //   if (res.data) {
      //     download(res.data, `商品档案_${this.dayjs(new Date()).format("YYYY-MM-DD HH:mm")}.xls`)
      //   } else {
      //     this.$message({
      //       message: '下载失败，请重试或联系管理员',
      //       type: 'error'
      //     })
      //   }
      // })
    },
    handleBatchEdit() {
      this.$refs.batchEditGoodsDialog.show()
    }
  },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() {
    window.addEventListener("keydown", this.keyupEnter);
  },
  deactivated() {
    window.removeEventListener("keydown", this.keyupEnter);
  },
};
</script>

<style lang="scss" scoped>
.rows {
  display: flex;
  justify-content: space-around;
}

.el-cascader {
  display: inline-block;
  position: relative;
  font-size: 14px;
  line-height: 40px;
}

.el-cascader__tags {
  position: absolute;
  left: 0;
  right: 30px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-wrap: wrap;
  line-height: normal;
  text-align: left;
  box-sizing: border-box;
}

.el-input.is-disabled .el-input__inner {
  color: #606266;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
}

::v-deep .Singleproduct {
  .el-form-item {
    margin-bottom: 30px !important;
  }

  .select-head-cont {
    // border: 1px solid #dcdfe6;
    // height: 32px;
    background-color: #fff;
    width: 200px;
    border-radius: 4px;
    display: block;
    position: relative;

    .selct-img {
      width: 10px;
      height: 10px;
      position: absolute;
      right: 10px;
      top: 0;
      bottom: 0;
      margin: auto;
    }
  }

  .el-tabs__item.is-active {
    color: #fff;
    background: #409eff;
    text-align: center !important;
  }

  .el-tabs--left .el-tabs__item.is-left {
    text-align: center !important;
  }

  el-tabs__nav-wrap::after {
    content: "";
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 2px;
    /* background-color: #E4E7ED; */
    z-index: 1;
  }

  .caketype {
    border: 1px solid #dcdfe6;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
    margin: 5px 0;
    width: 300px;
    position: relative;

    &:after {
      position: absolute;
      display: block;
      width: 0;
      height: 0;
      border-color: transparent;
      border-style: solid;
      top: 1px;
      margin-left: -6px;
      border-top-width: 0;
      border-bottom-color: #fff;
    }

    .el-radio-group {
      display: flex;
      flex-direction: column;
      padding: 10px 0;
      background-origin: padding-box;
      line-height: 30px;
      height: 170px;
      overflow: hidden;
      overflow-y: scroll;

      .el-radio {
        line-height: 30px;
      }
    }

    .el-checkbox-group {
      display: flex;
      flex-direction: column;
      padding: 10px 0;
      background-origin: padding-box;
      line-height: 30px;
      height: 170px;
      overflow: hidden;
      overflow-y: scroll;

      .el-radio {
        line-height: 30px;
      }
    }

    .buttontips {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
      margin-right: 10px;
    }
  }

  .specifications {
    .title {
      display: flex;
      line-height: 30px;
      color: #ff0000;
      font-size: 15px;

      img {
        width: 30px;
        height: 30px;
        margin-right: 8px;
      }
    }

    .rows {
      justify-content: space-around;
      display: flex;
      border-bottom: 1px solid #d9d9d9;
      margin-bottom: 10px !important;

      .el-form-item {
        display: flex;
        flex-direction: column;
        margin-bottom: 10px !important;

        .el-form-item__label {
          text-align: left;
        }

        .el-form-item__content {
          margin-left: 0 !important;
        }
      }

      .Delete_specification {
        margin-top: 20px;
        display: flex;
        line-height: 28px;

        span {
          font-size: 15px;
          color: #ff0000;
          padding-left: 5px;
        }

        i {
          font-size: 20px;
          line-height: 28px;
          color: #ff0000;
        }
      }

      .upload_ingredient {
        display: flex;
        line-height: 28px;

        i {
          font-size: 20px;
          line-height: 28px;
          color: green;
        }

        span {
          font-size: 15px;
          color: green;
          padding-left: 5px;
        }
      }

      .edit_ingredient {
        display: flex;
        line-height: 28px;

        i {
          font-size: 20px;
          line-height: 28px;
          color: #e2ba24;
        }

        span {
          font-size: 15px;
          color: #e2ba24;
          padding-left: 5px;
        }
      }
    }
  }
}

::v-deep .Commodityproduct {
  .el-form-item {
    margin-bottom: 30px !important;
  }

  .select-head-cont {
    // border: 1px solid #dcdfe6;
    // height: 32px;
    background-color: #fff;
    width: 200px;
    border-radius: 4px;
    display: block;
    position: relative;

    .selct-img {
      width: 10px;
      height: 10px;
      position: absolute;
      right: 10px;
      top: 0;
      bottom: 0;
      margin: auto;
    }
  }

  .el-tabs__item.is-active {
    color: #fff;
    background: #409eff;
    text-align: center !important;
  }

  .el-tabs--left .el-tabs__item.is-left {
    text-align: center !important;
  }

  el-tabs__nav-wrap::after {
    content: "";
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 2px;
    /* background-color: #E4E7ED; */
    z-index: 1;
  }

  .caketype {
    border: 1px solid #dcdfe6;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
    margin: 5px 0;
    width: 300px;
    position: relative;

    &:after {
      position: absolute;
      display: block;
      width: 0;
      height: 0;
      border-color: transparent;
      border-style: solid;
      top: 1px;
      margin-left: -6px;
      border-top-width: 0;
      border-bottom-color: #fff;
    }

    .el-radio-group {
      display: flex;
      flex-direction: column;
      padding: 10px 0;
      background-origin: padding-box;
      line-height: 30px;
      height: 170px;
      overflow: hidden;
      overflow-y: scroll;

      .el-radio {
        line-height: 30px;
      }
    }

    .el-checkbox-group {
      display: flex;
      flex-direction: column;
      padding: 10px 0;
      background-origin: padding-box;
      line-height: 30px;
      height: 170px;
      overflow: hidden;
      overflow-y: scroll;

      .el-radio {
        line-height: 30px;
      }
    }

    .buttontips {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
      margin-right: 10px;
    }
  }

  ::v-deep .specificationsslist {
    border: 1px solid #dcdfe6;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
    margin: 5px 0;
    width: 400px;
    height: 200px;
    position: absolute;
    width: 100%;
    z-index: 999;

    .el-tabs--left .el-tabs__header.is-left {
      width: 80%;
    }

    .close {
      position: absolute;
      top: 0;
      right: 0;
    }

    .el-checkbox-group {
      display: flex;
      flex-direction: column;
      padding: 10px 0;
      background-origin: padding-box;
      line-height: 30px;
      height: 170px;
      overflow: hidden;
      overflow-y: scroll;

      .el-radio {
        line-height: 30px;
      }
    }

    .buttontips {
      position: absolute;
      bottom: 0;
      right: 0;
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
      margin-right: 10px;
    }
  }

  .specifications {
    .lows {
      display: flex;
      justify-content: space-around;

      .el-form-item {
        display: flex;
        flex-direction: column;

        .el-form-item__label {
          text-align: left;
        }

        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
    }
  }
}

.app-container {

  .filter_container {
    .rows {
      // display: flex;
      // justify-content: space-between;
    }

    .el-form-item {
      margin-bottom: 22px !important;
    }

    .lows {
      display: flex;
      justify-content: flex-end;
    }

    .addshop {
      position: relative;
    }
  }

  .table_list {
    .warning-row {
      background: #fdf5e6;
      color: #e6a23c;
    }
  }
}

</style>
